package com.liuyi.netty.im.server.handle.storage;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * channel 储存
 *
 * @author Mr.Fmy
 * @since 2021-11-27
 */
public class ChannelStorage {

    private final static Map</** {@link ChannelId#asLongText()} **/String, ChannelId> channelIdMap = new ConcurrentHashMap<>();
    private final static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static final AttributeKey<User> USERINFO_ATTR = AttributeKey.valueOf("USERINFO");


    public static ChannelGroup get() {
        return channelGroup;
    }

    public static Channel get(String channelId) {
        return get(getChannelId(channelId));
    }

    public static Channel get(ChannelId channelId) {
        if (channelId != null) {
            return channelGroup.find(channelId);
        }
        return null;
    }

    public static ChannelId getChannelId(String channelId) {
        return channelIdMap.get(channelId);
    }

    public static boolean containsChannelId(String channelId) {
        return channelIdMap.containsKey(channelId);
    }

    public static void add(Channel channel, User user) {
        String id = channel.id().asLongText();
        if (!channelIdMap.containsKey(id)) {
            channel.attr(USERINFO_ATTR).set(user);
            channelIdMap.put(id, channel.id());
            channelGroup.add(channel);
        }
    }

    public static User getUserinfo(Channel channel) {
        return channel.attr(USERINFO_ATTR).get();
    }

    public static void remove(Channel channel) {
        channelIdMap.remove(channel.id().asLongText());
    }

//    public static void close(Channel channel) {
//        if (channel != null) {
//            channel.close();
//            User userinfo = getUserinfo(channel);
//            if (userinfo != null) {
//                LimManage.getUserStorage().offLine(userinfo.getUserId(), userinfo.getDevice());
//            }
//            channelIdMap.remove(channel.id().asLongText());
//        }
//    }
//
//    public static void close(String channelId) {
//        if (StrUtil.isNotEmpty(channelId)) {
//            close(getChannelId(channelId));
//        }
//    }
//
//    public static void close(ChannelId channelId) {
//        if (channelId != null) {
//            Channel channel = channelGroup.find(channelId);
//            if (channel != null) {
//                close(channel);
//            }
//        }
//    }
}
